/**
 * @description 债券借贷指令
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { PrimaryC, FirstHeaderC, SecondHeaderC, PrimaryGhostC, NoDataMaskC, ModalC, TableC } from '../../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Modal } from 'antd';
import style from './index.less';
import InstructionSend from './InstructionSend.js';
import PledgeBondsInfor from './PledgeBondsInfor.js';
import PositionAnalysis from './PositionAnalysis.js';
import RepurchaseInfor from './RepurchaseInfor.js';
import UnderlyingBondsInfor from './underlyingBondsInfor';
import { uniqueKey } from '../../../../../utils/commonFunc';
import config from './config';
const confirm = Modal.confirm;
const init = config.bondLending.init;
import { connect } from 'dva';
import 'moment/locale/zh-cn';

@Form.create()
@connect(({ exchangeAgreement, userM: user, trailM, loading }) => ({
  exchangeAgreement,
  user,
  trailM,
  loading,
}))
export default class BondLend extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      PositionAnalysis: null, //持仓页面数据参数
      RepurchaseInfor: null, //在途回购信息参数
      orderCategory: null, //申报类型
      orderSide: null, //委托方向,默认融入
      exchangeCode: init.exchangeCode.initValue, //交易市场,默认上交所
      selectData: [], //债券下拉
      PledgeBondsInforData: [], //用来回填质押券数据
      oldPledgeBondsInforData: [], //用来回填历史质押券数据
      UnderlyingBondsInforData: [], //用来回填标的券数据
      instructionSendData: [], //用来回填基础信息数据
      totalMoney1: null, //质押券面值总和
      totalMoney2: null, // 标的债券面值
      btnLoading: false, //按钮loading
      masking: true,
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '',
    };
  }

  componentDidMount() {
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //接收基础信息组件的交易市场、组合、委托方向、申报类型 ,质押券面值总和并且下发子组件
  getConfigData = (type, data) => {
    if (type == 'PositionAnalysis') {
      this.setState({
        PositionAnalysis: data,
      });
    }
    if (type == 'RepurchaseInfor') {
      this.setState({
        RepurchaseInfor: data,
      });
    }
    if (type == 'orderCategory') {
      this.setState({
        orderCategory: data,
      });
    }
    if (type == 'orderSide') {
      this.setState({
        orderSide: data,
      });
    }
    if (type == 'exchangeCode') {
      this.setState({
        exchangeCode: data,
      });
    }
    if (type == 'selectData') {
      this.setState({
        selectData: data,
      });
    }
    if (type == 'totalMoney1') {
      this.setState({
        totalMoney1: data,
      });
    }
    if (type == 'totalMoney2') {
      this.setState({
        totalMoney2: data,
      });
    }
    if (type == 'backfillData') {
      this.state.InstructionSend.reNewPledgeBondData(data.instructionSend, data);
      this.setState({
        PledgeBondsInforData: data.instructionSend.maatSecurityLendingPledge,
        oldPledgeBondsInforData: data.instructionSend.oldMaatSecurityLendingPledge ? data.instructionSend.oldMaatSecurityLendingPledge : [],
        UnderlyingBondsInforData: data.instructionSend.maatSecurityLendingStandard,
      });
    }
  };

  //取消
  cancel = () => {
    //清空页面
    this.state.InstructionSend.resetPage(1);
    this.state.InstructionSend.resetField(3);
    //关闭模态框
    this.props.rehandleSearch2();
    this.setState({ masking: true });
  };

  huitian = () => {
    this.state.UnderlyingBondsInfor.hutian();
  };

  //保存
  save = () => {
    const { uid } = this.state;
    // 1.拿到基础信息数据
    let InstructionSendData = this.state.InstructionSend.getpledgeList();
    // 2.拿到质押券数据
    let PledgeBondData = this.state.PledgeBondsInfor.getpledgeList();
    // 3.拿到标的券数据
    let UnderlyingBondData = this.state.UnderlyingBondsInfor.getpledgeList();

    if (InstructionSendData && InstructionSendData.trade16) {
      // 校验 质押券 标的券 至少要一条数据
      if (!(PledgeBondData && PledgeBondData.dataSource.length > 0 && UnderlyingBondData && UnderlyingBondData.length > 0)) {
        message.warning('请先新增质押券和标的券信息！');
        return;
      }
      // 5.组装数据
      InstructionSendData.trade16.maatSecurityLendingPledgeVo = PledgeBondData.dataSource;
      InstructionSendData.trade16.oldMaatSecurityLendingPledgeVo = PledgeBondData.dataSource1;
      InstructionSendData.trade16.maatSecurityLendingStandardVo = UnderlyingBondData;

      // 校验 借贷面额 = 标的券合计面值 = 质押券合计面值
      // if (!( UnderlyingBondData[0].totalFaceValue  == InstructionSendData.trade16.lendingeAmount  && PledgeBondData.totalMoney  == InstructionSendData.trade16.lendingeAmount)) {
      //   message.warning('基本信息借贷面额, 标的券借贷面额 ,质押券借贷面额总计 三个值需要相等！')
      //   return
      // }
      this.setState({
        btnLoading: true,
      });
      this.props
        .dispatch({
          type: 'exchangeAgreement/saveInstruction2',
          payload: {
            method: '0',
            uid: uid,
            ...InstructionSendData,
          },
        })
        .then((res) => {
          this.setState({
            btnLoading: false,
          });
          //清空页面
          this.state.InstructionSend.resetPage(1);
          this.state.InstructionSend.resetField(3);
          //关闭模态框 刷新列表
          this.props.rehandleSearch();
          this.setState({ masking: true });
          //清空交易对手下拉
          this.props.dispatch({
            type: 'exchangeAgreement/save',
            payload: {
              counterparty: [],
            },
          });
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        });
    }
  };

  //清空质押券 标的券信息
  resetPage = () => {
    this.state.UnderlyingBondsInfor.clearData();
    this.state.PledgeBondsInfor.clearData();
  };
  changeMasking = (value) => {
    if (value != undefined) {
      this.setState({ masking: false });
    }
  };

  //试算按钮点击
  trialOnClick = () => {
    const {
      user: { currentUser = {} },
    } = this.props;
    // 1.拿到基础信息数据
    let InstructionSendData = this.state.InstructionSend.getpledgeList();
    // 2.拿到质押券数据
    let PledgeBondData = this.state.PledgeBondsInfor.getpledgeList();
    // 3.拿到标的券数据
    let UnderlyingBondData = this.state.UnderlyingBondsInfor.getpledgeList();

    if (InstructionSendData && InstructionSendData.trade16) {
      // 校验 质押券 标的券 至少要一条数据
      if (!(PledgeBondData && PledgeBondData.dataSource.length > 0 && UnderlyingBondData && UnderlyingBondData.length > 0)) {
        message.warning('请先新增质押券和标的券信息！');
        return;
      }
      // 5.组装数据
      InstructionSendData.trade16.maatSecurityLendingPledgeVo = PledgeBondData.dataSource;
      InstructionSendData.trade16.oldMaatSecurityLendingPledgeVo = PledgeBondData.dataSource1;
      InstructionSendData.trade16.maatSecurityLendingStandardVo = UnderlyingBondData;

      this.setState({ trailModel: true }, () => {
        this.props.dispatch({
          type: 'trailM/trialData',
          payload: {
            method: '0',
            productCode: this.state.productCode, //产品code
            portfolioCode: this.state.portfolioCode, //组合code
            tenant: currentUser.tenant, //租户code
            businessType: '16',
            ...InstructionSendData,
          },
          callback: (res) => {
            if (res) {
              this.setState({
                trailColumns: res.columns,
                trailDataSource: res.dataSource,
              });
            } else {
              this.setState({
                trailColumns: [],
                trailDataSource: [],
              });
            }
          },
        });
      });
    }
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    this.setState({ masking: true, PositionAnalysis: undefined, RepurchaseInfor: undefined });
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  changeFee = (data) => {
    this.state.InstructionSend.changeFee('pledgedbondsamount', data ? data : undefined);
  };
  render() {
    const {
      exchangeAgreement: { portfolioList },
    } = this.props;
    return (
      <div>
        <Row className={style.index}>
          {(this.props.type == '1' || this.props.type == '2') && (
            <Col span={12}>
              <div>
                <FirstHeaderC title='持仓分析' />
              </div>
              <div className={style.bgcolor} style={{ position: 'relative' }}>
                <PositionAnalysis
                  PositionAnalysis={this.state.PositionAnalysis} //持仓页面数据参数
                  getConfigData={this.getConfigData} //抛出债券下拉
                />
                {this.state.masking && <NoDataMaskC height={'115px'} title={'请选择相对应的组合，加载数据！'} />}
              </div>

              <div style={{ marginTop: '13px' }}>
                <FirstHeaderC title='在途回购信息' />
              </div>
              <div className={style.bgcolor} style={{ position: 'relative' }}>
                <RepurchaseInfor
                  type={this.props.type}
                  RepurchaseInfor={this.state.RepurchaseInfor} //在途回购信息参数
                  getConfigData={this.getConfigData} //抛出双击回填数据
                />
                {this.state.masking && <NoDataMaskC height={'110px'} title={'请选择相对应的组合，加载数据！'} />}
              </div>
            </Col>
          )}

          <Col span={this.props.type == '1' || this.props.type == '2' ? 12 : 24}>
            {(this.props.type == '1' || this.props.type == '2') && (
              <div>
                <FirstHeaderC title='交易要素' />
              </div>
            )}

            <div style={{ marginBottom: '15px', marginTop: this.props.type == '1' || this.props.type == '2' ? '0px' : '-10px' }}>
              <PledgeBondsInfor
                type={this.props.type}
                initValue={this.props.initValue ? this.props.initValue : null} //详情页面初始化数据
                editInitValue={this.props.editInitValue ? this.props.editInitValue : null} //编辑页面数据回填
                pledgeBondsInforData={this.state.PledgeBondsInforData} //回填质押券信息
                oldPledgeBondsInforData={this.state.oldPledgeBondsInforData} //回填历史质押券信息
                selectData={this.state.selectData} //融入时债券下拉数据
                orderCategory={this.state.orderCategory} //申报类型
                orderSide={this.state.orderSide} //委托方向
                exchangeCode={this.state.exchangeCode} //交易所
                getConfigData={this.getConfigData} //抛出质押券表数据
                onRef={(ref) => this.setState({ PledgeBondsInfor: ref })} // 调用子组件方法，获取质押券表数据
              />
            </div>

            <SecondHeaderC title='标的券信息' />
            <div>
              <UnderlyingBondsInfor
                type={this.props.type}
                initValue={this.props.initValue ? this.props.initValue : null} //详情页面初始化数据
                editInitValue={this.props.editInitValue ? this.props.editInitValue : null} //编辑页面数据回填
                underlyingBondsInforData={this.state.UnderlyingBondsInforData} //回填标的券信息
                selectData={this.state.selectData} //融入时债券下拉数据
                orderCategory={this.state.orderCategory} //申报类型
                orderSide={this.state.orderSide} //委托方向
                exchangeCode={this.state.exchangeCode} //交易所
                getConfigData={this.getConfigData} //抛出标的券表数据
                changeFee={this.changeFee}
                onRef={(ref) => this.setState({ UnderlyingBondsInfor: ref })} // 调用子组件方法，获取质押券表数据
              />
            </div>

            <div style={{ marginTop: '15px' }}>
              <SecondHeaderC title='基本信息' />
            </div>

            <div className={style.bgcolor} style={{paddingTop:'10px'}}>
              <InstructionSend
                initValue={this.props.initValue ? this.props.initValue : null} //详情页面初始化数据
                editInitValue={this.props.editInitValue ? this.props.editInitValue : null} //编辑页面数据回填
                type={this.props.type}
                instructionSendData={this.state.instructionSendData} //回填基础信息
                getConfigData={this.getConfigData} //抛出基本信息数据
                totalMoney1={this.state.totalMoney1} //质押券面值总和
                totalMoney2={this.state.totalMoney2} //标的债券面值
                resetPage={this.resetPage} //重置页面
                huitian={this.huitian}
                portfolioCode={this.portfolioCode}
                productCode={this.productCode}
                changeMasking={this.changeMasking}
                onRef={(ref) => this.setState({ InstructionSend: ref })}
              />
            </div>
          </Col>

          {this.props.type == '1' || this.props.type == '2' ? (
            <div className={style.myBtn}>
              {/* {this.props.type == '1' && <PrimaryC
              loading={this.props.loading.effects['trailM/trialData'] === true}
              onClick={() => this.trialOnClick()}
              title={'试算'}
              style={{ marginRight: "10px" }}
            />} */}
              <PrimaryC title={this.props.type == '1' ? '确定' : '保存'} loading={this.state.btnLoading} style={{ margin: '10px' }} onClick={() => this.save()} />
              <PrimaryGhostC title='取消' style={{ margin: '10px' }} onClick={() => this.cancel()} />
            </div>
          ) : null}
        </Row>
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
